package com.sright.bcard.enterprise.web.controller;

import com.sright.bcard.common.service.share.excel.ExcelExport;
import com.sright.bcard.common.service.share.excel.info.DemoExcelInfo;
import com.sright.bcard.common.service.share.excel.style.DefaultExcelStyle;
import com.sright.bcard.common.service.share.excel.style.ExcelStyle;
import com.sright.bcard.common.service.share.excel.utils.ExcelType;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Validated
@RestController
@Slf4j
@RequestMapping("/excel")
public class ExcelDemoController {

    @GetMapping(value = "/exportOrder", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public void exportOrder(HttpServletResponse response) {
        try {
            List<Demo> exportList = Demo.getDemoList();
            if (CollectionUtils.isNotEmpty(exportList)) {
                OutputStream out = response.getOutputStream();
                response.setContentType("multipart/form-data;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
                String filename = "文件名" + LocalDate.now().format(fmt) + ".xlsx";
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                ExcelExport excel = new ExcelExport(DemoExcelInfo.class);
                List<DemoExcelInfo> list=new ArrayList<>();
                DataConvertUtils.convertDOList2DTOList(exportList,list, DemoExcelInfo.class);
                ExcelStyle excelStyle = new DefaultExcelStyle(ExcelType.xlsx);
                excel.exportExcel(list, "demo的导出", out, excelStyle);
            }
        } catch (IOException e) {
            log.info("exportOrder"+e.getMessage());
        }
    }

    @Data
    static class Demo implements Serializable {
        private static final long serialVersionUID = -9205874929448045313L;
        private Long id;

        private String userName;

        public static List<Demo> getDemoList() {
            List<Demo> demoList = new ArrayList<>();
            Demo demo1 = new Demo();
            demo1.setId(1L);
            demo1.setUserName("1111");

            Demo demo2 = new Demo();
            demo2.setId(2L);
            demo2.setUserName("2222");
            demoList.add(demo1);
            demoList.add(demo2);
            return demoList;
        }
    }

}
